package org.batatasframework.chart.columns;

import java.util.List;

import org.batatasframework.chart.ChartCell;

public abstract class AbstractValueColumn<T> extends AbstractChartColumn{

	/** 可以指定当某个字段为null时，需要显示什么样的信息，默认为""空字符串，也可以指定为"-"或"/"等字符 */
	protected String nullValue = "";
	
	protected AbstractValueColumn(String name) {
		super(name);
	}
	
	public void setNullValue(String nullValue) {
		this.nullValue = nullValue;
	}
	
	@Override
	public final ChartCell newCell() {
		return createCell();
	}
	
	protected ChartCell createCell(){
		return new InternalChartCell();
	}
	
	protected abstract T internalParseValue(Object[] row);

	protected class InternalChartCell extends AbstractChartCell<T>{
		
		@Override
		public void read(Object[] row) {
			T value = internalParseValue(row);
			this.value = internalAdd(this.value, value);
		}
		
		private T internalAdd(T oldValue, T newValue){
			if(oldValue == null) return newValue;
			if(newValue == null) return oldValue;
			return mergedValue(oldValue, newValue);
		}
		
		@Override
		public final void add(ChartCell augend) {
			@SuppressWarnings("unchecked")
			InternalChartCell cellAugend = (InternalChartCell) augend;
			this.value = internalAdd(this.value, cellAugend.value);
		}
		
		@Override
		public String toString() {
			Object value = getValue();
			if(null == value) return nullValue;
			return value.toString();
		}
		
		@Override
		public void write(List<Object> item) {
			item.add(toString());
		}

		public Object getValue() {
			return resolveValue(value);
		}
	}
	
	protected Object resolveValue(T value){
		return value;
	}
	
	protected T mergedValue(T oldValue, T newValue){ 
		return newValue; 
	}
}
